﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;

namespace XW.Utils
{
    /// <summary>
    /// 对象扩展
    /// </summary>
    public static class ObjectExtensions
    {

        ///// <summary>
        ///// 利用序列化进行对象拷贝,要求对象是序列化的
        ///// </summary>
        ///// <typeparam name="T">对象类型</typeparam>
        ///// <param name="item">源对象</param>
        ///// <returns>克隆对象</returns>
        //public static T Clone<T>(this T item) where T : class
        //{
        //    T result = default(T);
        //    if (null != item)
        //    {
        //        return TypeSerializer.Clone(item);
        //        //MemoryStream ms = new MemoryStream();
        //        //BinaryFormatter bf = new BinaryFormatter();
        //        //bf.Serialize(ms, item);
        //        //ms.Seek(0, SeekOrigin.Begin);
        //        //result = bf.Deserialize(ms) as T;
        //        //ms.Close();
        //    }
        //    return result;
        //}
        /// <summary>
        /// Deeps the clone.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj">The object.</param>
        /// <returns></returns>
        public static T DeepClone<T>(this T obj)
        {
            if (obj == null)
            {
                return obj;
            }
            // Disable the warning.
#pragma warning disable SYSLIB0011
            using (var ms = new MemoryStream())
            {
                var formatter = new BinaryFormatter();
                formatter.Serialize(ms, obj);
                ms.Position = 0;

                return (T)formatter.Deserialize(ms);
            }
            // Re-enable the warning.
#pragma warning restore SYSLIB0011
        }
    }
}
